import * as step from '@flow-step/step-toolkit'
import process from 'process'
import {convertToUpperCase} from './util'
import {getParams} from './params'
import fetch from 'node-fetch';

interface ImageInfo {
  type: string;
  artifact: string;
  DOCKER_URL: string;
  dockerUrl: string;
  dockerTag: string;
}

interface DeployPayload {
  containerName: string;
  image: string;
  deployName: string;
}

async function runStep(): Promise<void> {
	try {
		const params = getParams()
		step.info(`PIPELINE_ID=${params.pipelineID}`)
		step.info(`PIPELINE_NAME=${params.pipelineName}`)
		step.info(`BUILD_NUMBER=${params.buildNumber}`)
		step.info(`WORK_SPACE=${params.workSpace}`)
		step.info(`PROJECT_DIR=${params.projectDir}`)
		step.info(`BUILD_JOB_ID=${params.buildJobID}`)

		//const abc = process.env.abc ? process.env.abc as string : ''
		//step.info(`Hello from flow-step EeenetXkubeAliyunFlow, custom param abc=${abc}, upper value=${convertToUpperCase(abc)}`)

		step.info(`Log other step.yaml item value`)
		// 获取其它 step.yaml 定义的变量
		const XKUBEAPIKEY = process.env["XKUBEAPIKEY"] as string
		step.info(`XKUBEAPIKEY=${XKUBEAPIKEY}`)

		const CLUSTERID = process.env["CLUSTERID"] as string
		step.info(`exclusion=${CLUSTERID}`)

		const NAMESPACE = process.env["NAMESPACE"] as string
		step.info(`NAMESPACE=${NAMESPACE}`)

		const DEPLOYTYPE = process.env["DEPLOYTYPE"] as string
		step.info(`DEPLOYTYPE=${DEPLOYTYPE}`)

		const DEPLOYNAME = process.env["DEPLOYNAME"] as string
		step.info(`DEPLOYNAME=${DEPLOYNAME}`)

		const CONTAINER = process.env["CONTAINER"] as string
		step.info(`CONTAINER=${CONTAINER}`)

		const IMAGE = process.env["IMAGE"] as string
		step.info(`IMAGE=${IMAGE}`)

		if (!IMAGE) {
		  throw new Error('IMAGE environment variable is required');
		}
			// 解析JSON字符串
		const imageInfo: ImageInfo = JSON.parse(IMAGE);

		// 提取dockerUrl
		const { dockerUrl } = imageInfo;

		// 构造新JSON
		const payload: DeployPayload = {
		  containerName: CONTAINER || '',
		  image: dockerUrl,
		  deployName: DEPLOYNAME || ''
		};

		console.log('Sending payload:', JSON.stringify(payload, null, 2));
		
		const apiUrl = `https://xkube-demo.eeenet.net/public/cicd/UpdateImage?clusterId=${CLUSTERID}&nameSpace=${NAMESPACE}&deployType=${DEPLOYTYPE}&deployName=${DEPLOYNAME}`;

		// 发送POST请求
		const response = await fetch(apiUrl, {
		  method: 'POST',
		  headers: {
			'Content-Type': 'application/json',
			'xkey': XKUBEAPIKEY
		  },
		  body: JSON.stringify(payload)
		});

		const result = await response.json();
		
		if (response.ok) {
		  console.log('Success:', result);
		} else {
		  console.error('Failed:', response.status, result);
		  process.exit(1);
		}
	
	} catch (error) {
		console.error('Error:', error);
		process.exit(1);
	}
}

runStep()
    .then(function() {
        step.success('run step successfully!')
    })
    .catch(function(err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
